import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:charset/charset.dart';
import 'package:file_picker/file_picker.dart';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:jar_replacer/about.dart';
import 'package:jar_replacer/setting.dart';
import 'package:jar_replacer/jar_place.dart';
import 'package:path/path.dart' as p;
import 'package:file_selector/file_selector.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'config_controller.dart';
import 'theme_controller.dart';

// import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:window_manager/window_manager.dart';
import 'package:fluentui_system_icons/fluentui_system_icons.dart' as icon;
import 'package:flutter_localization/flutter_localization.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; // <-- 必须导入这个包



Future<void> main() async {
  runZonedGuarded(() async {
    WidgetsFlutterBinding.ensureInitialized();
    // Must add this line.
    await windowManager.ensureInitialized();

    WindowOptions windowOptions = WindowOptions(
      size: Size(1200, 850),
      center: true,
      backgroundColor: Colors.blue,
      skipTaskbar: false,
      titleBarStyle: TitleBarStyle.hidden,
    );
    windowManager.waitUntilReadyToShow(windowOptions, () async {
      await windowManager.show();
      await windowManager.focus();
    });
    ///
    ///

    // 设置初始窗口标题
    windowManager.setTitle("JAR替换与重新打包工具");
    // 禁用双击标题栏时的最大化行为
    windowManager.setResizable(false);

    // 这里的代码将在一个新的 Zone 中执行
    // 初始化GetX控制器
    Get.put(ConfigController());
    Get.put(ThemeController());
    // 输出应用文档路径
    printPreferencesPath();

    // 你可以根据这个路径手动拼接或直接导航到该目录
    await FlutterLocalization.instance.ensureInitialized();
    final FlutterLocalization localization = FlutterLocalization.instance;
    runApp(
      GetBuilder<ThemeController>(
        builder: (themeController) {
          return FluentApp(
            title: 'JAR替换与重新打包工具',
            home: const MyApp(),
            themeMode: themeController.isDark ? ThemeMode.dark : ThemeMode.light,
            theme: FluentThemeData.light(),
            darkTheme: FluentThemeData.dark(),
            // 添加Fluent本地化代理
            localizationsDelegates: [
              ...localization.localizationsDelegates,
              FluentLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
            ],
            supportedLocales: [
              Locale('en'),
              Locale('zh'),
            ],
          );
        },
      ),
    );
    // 模拟一个会抛出异常的异步操作
  }, (error, stackTrace) {
    // 处理捕获到的错误
    print('捕获到的错误: $error');
    print('堆栈跟踪: $stackTrace');
  });
}

void printPreferencesPath() async {
  // 获取应用的文档目录
  Directory? appDocDir = await getApplicationDocumentsDirectory();

  // shared_preferences 在 Windows 上会在文档目录下创建一个子目录
  // 实际路径是 appDocDir.path + '/shared_preferences/<package_name>_preferences.json'

  print('应用文档目录: ${appDocDir?.path}');
  // 你可以根据这个路径手动拼接或直接导航到该目录
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetBuilder<ThemeController>(
      builder: (themeController) {
        return FluentApp(
          title: 'Flutter Demo',
          // 自定义亮色主题
          color: themeController.color,
          // 强调色
          theme: FluentThemeData(
            brightness: Brightness.light,
            fontFamily: Platform.isWindows ? "微软雅黑" : null,
            accentColor: themeController.color,
          ),
          darkTheme: FluentThemeData(
              brightness: Brightness.dark,
              fontFamily: Platform.isWindows ? "微软雅黑" : null,
              scaffoldBackgroundColor: Colors.black,
              accentColor: themeController.color),
          themeMode: themeController.isDark ? ThemeMode.dark : ThemeMode.light,
          localizationsDelegates: const [
            FluentLocalizations.delegate,
            GlobalMaterialLocalizations.delegate, // <-- 正确使用
            // 4. Flutter 官方提供的基础 Widget 本地化代理
            GlobalWidgetsLocalizations.delegate,   // <-- 正确使
          ],
          supportedLocales: const [
            Locale('en', 'US'),
            Locale('zh', 'CN'),
          ],
          home: JarReplacerMain(),
        );
      },
    );
  }
}

class JarReplacerMain extends StatefulWidget {
  @override
  State<JarReplacerMain> createState() => _JarReplacerMainState();
}

class _JarReplacerMainState extends State<JarReplacerMain> {
  int topIndex = 0;
  PaneDisplayMode displayMode = PaneDisplayMode.compact;

  // 是否已放大
  bool maximize = false;

  // 是否移动到关闭按钮
  bool _isHovered = false;

  @override
  void initState() {
    super.initState();
  }

  List<NavigationPaneItem> items = [
    PaneItem(
        icon: const Icon(FluentIcons.home),
        title: const Text('主页'),
        body: const JarReplacer()),
    PaneItemSeparator(),
    PaneItem(
        icon: const Icon(FluentIcons.settings),
        title: const Text('设置'),
        body: const Setting()),
    PaneItem(
      icon: const Icon(icon.FluentIcons.info_48_regular),
      title: const Text('关于'),
      body: const About(),
    ),
  ];

  /**
   * 缩小
   */
  onMinimize() {
    windowManager.minimize();
  }

  /**
   * 放大
   */
  onMaximize() async {
    if (await windowManager.isMaximized()) {
      windowManager.unmaximize();
      setState(() {
        maximize = false;
      });
    } else {
      windowManager.maximize();
      setState(() {
        maximize = true;
      });
    }
  }

  /**
   * 关闭
   */
  onClose() {
    windowManager.close();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ThemeController>(builder: (themeController) {
      return NavigationView(
        appBar: const NavigationAppBar(
            automaticallyImplyLeading: false,
            title: DragToMoveArea(
            child: Align(
              alignment: AlignmentDirectional.centerStart,
              child: Text('BootJar替换工具'),
            ),
          ),
            actions: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              mainAxisSize: MainAxisSize.max,
              children: [
                WindowButtons()
              ],
            ),),
        pane: NavigationPane(
          selected: topIndex,
          onItemPressed: (index) {
            if (index == topIndex) {
              if (displayMode == PaneDisplayMode.open) {
                setState(() => this.displayMode = PaneDisplayMode.compact);
              } else if (displayMode == PaneDisplayMode.compact) {
                setState(() => this.displayMode = PaneDisplayMode.open);
              }
            }
          },
          onChanged: (index) => setState(() => topIndex = index),
          displayMode: displayMode,
          items: items,
        ),
      );
    });
  }


}

class WindowButtons extends StatelessWidget {
  const WindowButtons({super.key});

  @override
  Widget build(BuildContext context) {
    final FluentThemeData theme = FluentTheme.of(context);

    return SizedBox(
      width: 138,
      height: 50,
      child: WindowCaption(
        brightness: theme.brightness,
        backgroundColor: Colors.transparent,
      ),
    );
  }
}
